package com.atguigu.redislock.test;


import java.util.Random;

class House
{
    static int x = 5;

    ThreadLocal<Integer> individualSale = ThreadLocal.withInitial(() -> 0);

    public void sale()
    {
        individualSale.set(individualSale.get()+1);
    }
}





/**
 * @auther zzyy
 * @create 2022-10-31 8:58
 */
public class ThreadLocalDemo
{
    public static void main(String[] args)
    {
        House house1 = new House();
        House house2 = new House();

        /*System.out.println(Thread.currentThread().getName()+"\t"+house.individualSale.get());

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t"+house.individualSale.get());
        },"t1").start();

        new Thread(() -> {
            System.out.println(Thread.currentThread().getName()+"\t"+house.individualSale.get());
        },"t2").start();*/

        /*for (int i = 1; i <=5; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName()+"\t"+house.individualSale.get());
                    house.individualSale.set(house.individualSale.get()+1);
                    System.out.println(Thread.currentThread().getName()+"\t"+house.individualSale.get());
                } finally {
                    house.individualSale.remove();
                }
            },String.valueOf(i)).start();
        }*/

        for (int i = 1; i <=5; i++) {
            new Thread(() -> {
                for (int j = 1; j <= new Random().nextInt(5)+1; j++) {
                    house1.sale();
                }
                System.out.println(Thread.currentThread().getName()+"\t"+"号销售卖出："+house1.individualSale.get());
            },String.valueOf(i)).start();
        }
    }
}
